from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from OAuth.models import OAuthQQUser
from OAuth.utils import OAuthQQ
from .serializers import OAuthQQUserSerializer
from carts.utils import merge_cart_to_redis
# Create your views here.


class OAuthQQUserUrl(APIView):
    """获取QQ登录的url"""
    def get(self, request):
        # next 用户QQ登录成功后进入美多商城的哪个网址,即跳转的页面
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.generate_login_url()

        # login_url qq登录网址
        return Response({'login_url': login_url})


# class OAuthQQUserView(APIView):
class OAuthQQUserView(CreateAPIView):
    """QQ登录的用户"""

    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        """获取qq登录的用户数据"""
        try:
            # 获取用户的code
            code = request.query_params.get('code')
        except:
            return Response({'message': 'code获取失败'})

        oauth = OAuthQQ()
        access_token = oauth.get_access_token(code)

        # 获取用户的openid
        openid = oauth.get_openid(access_token)

        # 判断用户是否存在
        try:
            # 根据openid获取QQ用户,如果没有access_token是获取不到的，因为它是凭借access_token向QQ服务器请求用户的openid
            qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 用户第一次使用QQ登录,生成绑定用户身份的access_token
            token = oauth.generate_save_access_token(openid)
            return Response({'token': token})
        else:
            # 不是第一次使用QQ登录，登录成功，返回jwt_token，以后登录验证用户身份
            # 找到用户，QQ绑定用户
            user = qq_user.user

            # 生成jwt_token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            pay_load = jwt_payload_handler(user)
            token = jwt_encode_handler(pay_load)

            # response = Response({
            #     'token': token,
            #     'user_id': user.id,
            #     'username': user.username
            # })
            # return response

            response = Response({
                'user_id': user.id,
                'username': user.usename,
                'token': token
            })

            # 合并购物车
            # 不是第一次QQ登录， 再次登录要合并购物车信息
            response = merge_cart_to_redis(request, user, response)

            return response

    def post(self, request, *args, **kwargs):
        #  使用序列化器中添加的用户信息进行登录， 直接使用原来已有的方法
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_to_redis(request, self.user, response)
        return response
